<?php

// put full path to Smarty.class.php

$smartyPath = "/home/geeka813/Smarty-3.1.13/libs";
$publicHtml = "/home/geeka813/public_html";
$base_css = "/css";
$base_images = "/images";

// contains all smarty declarations
require_once($publicHtml . '/config.php');
require_once($publicHtml . '/menu.php');



$log->LogInfo("Processing scratch page");

$log->LogInfo("Request Parameters = " . print_r($_REQUEST, TRUE));

if($_REQUEST['upload'])
{
   $log->LogInfo("Files info " . print_r($_FILES, TRUE));
   
   $fileName = $_FILES["file"]["tmp_name"];
   
   if($fileName=="")
   {
   	$log->LogInfo("Upload - file name not found");
   	$response = new stdClass();
   	$response->response = "failure";
   	$response->reason = "Upload File not specified";
   	echo json_encode($response);
   	return;
   }
   
   $origFileName = urlencode($_FILES["file"]["name"]);
   
   $log->LogInfo("Upload - found filename = {$fileName}, origFileName = {$origFileName}");
   
   // TODO - Insert a game entry into the db
   // then create a folder with that id in the scratch projects folder
   // put it in a awaiting approval state - in case some idiots are uploading crap - also for defamatory entries
   
 
   $sql = $pdo->prepare("INSERT INTO `scratch_game` (`game_info`) VALUES (:game_info)");
   $sql->bindValue(':game_info', '{"original_name": "' . $origFileName . '"}');
   $sql->execute();
   $lastInsertId = $pdo->lastInsertId();
   
   $newDir = '/home/geeka813/public_html/Scratch/projects/' . $lastInsertId;
   
   if(!mkdir($newDir))
   {
   	$log->LogInfo("Upload - failed to create directory '{$newDir}'");
   	$response = new stdClass();
   	$response->response = "failure";
   	$response->reason = "directory creation error";
   	echo json_encode($response);
   	return;
   }
      	
  $log->LogInfo("Upload - create directory '{$newDir}' OK");
   
   if(move_uploaded_file($fileName,"{$newDir}/{$lastInsertId}.sb")) 
   {
      $log->LogInfo("File moved OK");
      $response = new stdClass();
      $response->response = "success";
      $response->reason = "File uploaded ok";
      $response->fileid = $lastInsertId;
      echo json_encode($response);
      return;
   }
   else
   {
      $log->LogInfo("Failed to move file");
      $response = new stdClass();
      $response->response = "failure";
      $response->reason = "move file failed";
      echo json_encode($response);
      return;
   }
}

if($_REQUEST['newgame'])
{

	$name = $_REQUEST['name'];
	$email = $_REQUEST['email'];
	$instructions = $_REQUEST['instructions'];
	$gameid = $_REQUEST['gameid'];
	$gametitle = $_REQUEST['gametitle'];
	$gamedescription = $_REQUEST['gamedescription'];
	$imagename = $_REQUEST['imagename'];
	
	// TODO tweak SQL to only pick up a pending game - don't want anyone out there altering approved games!!
	$sql = $pdo->prepare("SELECT game_info FROM scratch_game WHERE id=:gameid");
	$sql->bindValue(':gameid', $gameid);
	$sql->execute();
	
	$row = $sql->fetch();

	$log->LogInfo("Row details = " . print_r($row, TRUE));
	
	$log->LogInfo("Fetching game details for game {$gameid}");
	
	$gameinfo = $row['game_info'];
	$gameInfoObj = json_decode($gameinfo);
	
	$log->LogInfo("decoded game info - " . print_r($gameInfoObj, TRUE));
	
	$newInfo = new stdClass();
	$newInfo->name = $name;
	$newInfo->email = $email;
	$newInfo->instructions = $instructions;
	$newInfo->gametitle= $gametitle;
	$newInfo->gamedescription = $gamedescription;
	$newInfo->original_file = $gameInfoObj->original_name;
	$newInfo->imagename = $imagename;
	
	$gameinfo = json_encode($newInfo);
	$log->LogInfo("encoded game info - " . print_r($gameinfo, TRUE));
	
	// TODO check row result - nasty spamers out there u know!!!
	
	$sql = $pdo->prepare("UPDATE scratch_game SET game_info=:game_info WHERE id=:gameid");
        $sql->bindValue(':game_info', $gameinfo);
        $sql->bindValue(':gameid', $gameid);
        $sql->execute();
        
        $response = new stdClass();
        $response->response = "success";
        $response->reason = "Game coming soon";
        echo json_encode($response);
        
        $obj = new stdClass();
        $obj->type = "gameupload";
        $obj->name = $name;
        $obj->email = $email;
        $obj->gameurl="www.geekawhat.com/scratchgame.php?gid=" . $gameid;
        
        sendEmail($obj);
        
        return;
}

function sendEmail($messageDetails)
{
   global $log, $smarty;
   $log->LogInfo("In sendEmail, messageDetails = " . print_r($messageDetails, TRUE));
   
   
   $to = $messageDetails->email;
   $log->LogInfo("here1");
   $subject = "Scratch Upload Confirmation | GeekaWhat";
      $log->LogInfo("here2");

   
   $message = "Hello! This is a simple email message.";
      $log->LogInfo("here3");

   $from = "scratchprojects@geekawhat.com";
      $log->LogInfo("here4");

   $headers = "From:" . $from . "\r\n";
   $headers .= "Reply-To:" . $from . "\r\n";
      $log->LogInfo("here6");


   $headers .= "MIME-Version: 1.0\r\n";
      $log->LogInfo("here7");

   $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
      $log->LogInfo("here8");

   
   $log->LogInfo("about to fetch email html for message to {$to}");
   
   $smarty->assign("name", $messageDetails->name);
   $smarty->assign("base_css", "www.geekawhat.com/css");
   $smarty->assign("base_images", "www.geekawhat.com/images");
         $log->LogInfo("here9");

   $message = $smarty->fetch("email.tpl");
   
   $log->LogInfo("Sending email message is '{$message}'");

   mail($to,$subject,$message,$headers);

}

$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$menuSql = "SELECT data FROM page_item WHERE pageid=4";
  			
$result = $pdo->query($menuSql);
//# Map results to object
$results = $result->fetchAll(PDO::FETCH_ASSOC);   		
		
$carousel1 = array();
$menu1 = array();
$slider1 = array();
$games = array();

$menus = new stdClass();

$menus->carousel1 = array();
$menus->menu1 = array();
$menus->slider1 = array();
$menus->games = array();

populateMenuItems($results, $log, $menus);

$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$menuSql = "SELECT id,game_info FROM scratch_game WHERE status='approved'";
  			
$result = $pdo->query($menuSql);
//# Map results to object
//$result->setFetchMode(PDO::FETCH_CLASS, 'pageid');
$results = $result->fetchAll(PDO::FETCH_ASSOC);   		

$log->LogInfo("scratch_game results " . print_r($results, TRUE));


if(sizeof($results) > 0)
{
	foreach($results as $row)
	{
		$dataObj = json_decode($row['game_info']);
		$log->LogInfo("Processing item game dataObj = " . print_r($dataObj, TRUE));
			
		$obj = new stdClass();
					
		$obj->name = $dataObj->name;
		//$obj->email = $dataObj->email;
		$obj->gameinstructions = $dataObj->instructions;
		$obj->imageurl = '/Scratch/projects/' . $row['id'] . '/' . $dataObj->imagename;
		$obj->clickurl = '/scratchgame.php?gid=' . $row['id'];
		$obj->gametitle = $dataObj->gametitle;
					
		$games[] = $obj;
		
		$log->LogInfo("Games array = " . print_r($games, TRUE));
        }
}

$log->LogInfo("carousel1 = " . print_r($menus->carousel1, TRUE));
$log->LogInfo("menu1 = " . print_r($menus->menu1, TRUE));
$log->LogInfo("games = " . print_r($menus->games, TRUE));

$smarty->assign("carousel1", $menus->carousel1);
//$smarty->assign("games", $menus->games);
$smarty->assign("games", $games);
$smarty->assign("menu1", $menus->menu1);
$smarty->assign("slider1", $menus->slider1);
$smarty->assign("base_css", $base_css);
$smarty->assign("base_images", $base_images);

$crumbTrail = array();
$crumbTrail["Home > "] = "index.php";
$crumbTrail["Scratch"] = "";

$smarty->assign("crumbtrail", $crumbTrail);


$smarty->display('scratch.tpl');

?>